#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: main.py
@time: 2025/3/6 19:35
@desc: 
"""

import tkinter as tk
from tkinter import ttk
import psutil
import threading
import time
import requests
import queue
from datetime import datetime
import configparser

# 配置解析
config = configparser.ConfigParser()
config.read('config.ini')

# 常量定义
REFRESH_INTERVAL = 1  # 系统监控刷新间隔（秒）
WEATHER_UPDATE_INTERVAL = 600  # 天气更新间隔（秒）
HEFENG_API_URL = "https://devapi.qweather.com/v7/weather/now"
HEFENG_API_KEY = config.get('Weather', 'api_key', fallback='YOUR_API_KEY')
CITY = config.get('Weather', 'city', fallback='beijing')


class SystemMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("系统监控与天气 v1.0")
        self.root.geometry("800x400")
        self.root.resizable(True, True)

        # 数据队列
        self.data_queue = queue.Queue()

        # 网络速度计算变量
        self.last_net_io = psutil.net_io_counters()
        self.last_net_time = time.time()

        # 创建界面组件
        self.create_widgets()

        # 启动后台线程
        self.start_threads()

    def create_widgets(self):
        # 时间显示区域
        self.time_label = tk.Label(self.root, text="", font=("Arial", 14))
        self.time_label.pack(anchor=tk.NE, padx=10, pady=5)

        # 系统监控框架
        sys_frame = ttk.LabelFrame(self.root, text="系统监控")
        sys_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10)

        self.cpu_label = ttk.Label(sys_frame, text="CPU 使用率: -%")
        self.cpu_label.pack(padx=5, pady=5)

        self.mem_label = ttk.Label(sys_frame, text="内存使用: -GB / -GB")
        self.mem_label.pack(padx=5, pady=5)

        self.net_label = ttk.Label(sys_frame, text="网速: ↓- KB/s ↑- KB/s")
        self.net_label.pack(padx=5, pady=5)

        # 天气信息框架
        weather_frame = ttk.LabelFrame(self.root, text="实时天气")
        weather_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10)

        self.weather_temp = ttk.Label(weather_frame, text="温度: --℃", font=("Arial", 16))
        self.weather_temp.pack(padx=5, pady=5)

        self.weather_desc = ttk.Label(weather_frame, text="天气状况: -", font=("Arial", 12))
        self.weather_desc.pack(padx=5, pady=5)

        self.weather_humidity = ttk.Label(weather_frame, text="湿度: --%")
        self.weather_humidity.pack(padx=5, pady=5)

        self.weather_wind = ttk.Label(weather_frame, text="风速: --km/h")
        self.weather_wind.pack(padx=5, pady=5)

    def start_threads(self):
        # 系统监控线程
        threading.Thread(target=self.update_system_info, daemon=True).start()

        # 天气更新线程
        threading.Thread(target=self.update_weather, daemon=True).start()

        # GUI更新线程
        self.root.after(100, self.update_gui)

    def update_system_info(self):
        while True:
            # CPU使用率
            cpu_percent = psutil.cpu_percent(interval=0.5)

            # 内存信息
            mem = psutil.virtual_memory()
            mem_usage = f"{mem.used / 1024 ** 3:.1f}GB / {mem.total / 1024 ** 3:.1f}GB"

            # 网络速度计算
            current_net_io = psutil.net_io_counters()
            current_time = time.time()
            time_delta = current_time - self.last_net_time
            download_speed = (current_net_io.bytes_recv - self.last_net_io.bytes_recv) / time_delta
            upload_speed = (current_net_io.bytes_sent - self.last_net_io.bytes_sent) / time_delta

            # 更新网络状态变量
            self.last_net_io = current_net_io
            self.last_net_time = current_time

            # 组装数据
            sys_data = {
                'cpu': cpu_percent,
                'mem': mem_usage,
                'net_down': download_speed / 1024,  # KB/s
                'net_up': upload_speed / 1024
            }

            # 放入队列
            self.data_queue.put(('system', sys_data))

            # 休眠
            time.sleep(REFRESH_INTERVAL)

    def update_weather(self):
        while True:
            try:
                params = {
                    "location": CITY,
                    "key": HEFENG_API_KEY
                }
                response = requests.get(HEFENG_API_URL, params=params, timeout=10)
                data = response.json()

                if data.get('code') == '200':
                    now = data['now']
                    weather_data = {
                        'temp': now['temp'],
                        'desc': now['text'],
                        'humidity': now['humidity'],
                        'wind': now['windSpeed']
                    }
                    self.data_queue.put(('weather', weather_data))
                else:
                    self.data_queue.put(('weather_error', data.get('msg', '未知错误')))

            except Exception as e:
                self.data_queue.put(('weather_error', str(e)))

            time.sleep(WEATHER_UPDATE_INTERVAL)

    def update_gui(self):
        try:
            while not self.data_queue.empty():
                data_type, data = self.data_queue.get_nowait()

                if data_type == 'system':
                    self.cpu_label.config(text=f"CPU 使用率: {data['cpu']:.1f}%")
                    self.mem_label.config(text=f"内存使用: {data['mem']}")
                    self.net_label.config(text=f"网速: ↓{data['net_down']:.1f} KB/s "
                                               f"↑{data['net_up']:.1f} KB/s")
                elif data_type == 'weather':
                    self.weather_temp.config(text=f"温度: {data['temp']}℃")
                    self.weather_desc.config(text=f"天气状况: {data['desc']}")
                    self.weather_humidity.config(text=f"湿度: {data['humidity']}%")
                    self.weather_wind.config(text=f"风速: {data['wind']}km/h")
                elif data_type == 'weather_error':
                    self.weather_temp.config(text="天气获取失败", foreground='red')
                    self.weather_desc.config(text=data)

            # 更新时间
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.time_label.config(text=current_time)

        finally:
            self.root.after(100, self.update_gui)


if __name__ == "__main__":
    # 创建配置文件示例
    if not config.has_section('Weather'):
        config.add_section('Weather')
        config.set('Weather', 'api_key', 'YOUR_API_KEY')
        config.set('Weather', 'city', 'beijing')
        with open('config.ini', 'w') as f:
            config.write(f)
    root = tk.Tk()
    app = SystemMonitorApp(root)
    root.mainloop()